<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="form.phone"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[
          {
            validator: validatePhone,
            message: '请输入有效的手机号',
          },
        ]"
      />
      <van-field
        v-model="form.email"
        name="邮箱"
        label="邮箱"
        placeholder="邮箱"
        :rules="[
          {
            validator: validateEmail,

            message: '请输入有效的邮箱号码',
          },
        ]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import { ref, reactive } from "vue";
const form = reactive({
  phone: "",
  email: "",
});
const validatePhone = (value, rule) => {
  const regexPhone = /^1[3-9]\d{9}$/;
  const regexEmail = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/;
  let result = false;
  //   至少一个有值通过校验
  if (regexPhone.test(value) || regexEmail.test(form.email)) {
    result = true;
    if(value && !regexPhone.test(value)){
        result = false

    }
  }
  return result;
};
const validateEmail = (value, rule) => {
  const regexPhone = /^1[3-9]\d{9}$/;
  const regexEmail = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/;
  let result = false;
  //   至少一个有值通过校验
  if (regexEmail.test(value) || regexPhone.test(form.phone)) {
    result = true;
    if(value && !regexEmail.test(value)){
        result = false

    }
  }
  return result;
};
const onSubmit = (values) => {
  console.log("校验通过", values);
};
</script>
<style lang="scss" scoped></style>
